package com.xuan.pmh.activity;

import java.util.Map;

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.xuan.pmh.R;
import com.xuan.pmh.bean.GsonBean;
import com.xuan.pmh.bean.User;
import com.xuan.pmh.util.ActivityUtil;
import com.xuan.pmh.util.FinalValue;
import com.xuan.pmh.util.HttpUtil;
import com.xuan.pmh.util.ShareUtil;
import com.xuan.pmh.util.ToastUtil;


public class MainActivity extends HttpActivity {

	private EditText etUserId,etPassword,etUrl;
	private Button btLogin,btRegister,btSureUrl;
	private Spinner spRole;
	private User user = new User();
	
	@Override
	public int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.activity_main;
	}

	@Override
	public void setUI() {
		// TODO Auto-generated method stub
		etUserId = (EditText)findViewById(R.id.etUserId);
		etPassword = (EditText)findViewById(R.id.etPassword);
		etUrl = (EditText)findViewById(R.id.etUrl);
		btLogin = (Button) mFindViewAndSetOnClick(R.id.btLogin);
		btRegister = (Button) mFindViewAndSetOnClick(R.id.btRegister);
		btSureUrl = (Button) mFindViewAndSetOnClick(R.id.btSureUrl);
		spRole = (Spinner)findViewById(R.id.spRole);
		
	}

	@Override
	public void OnClickListener(View view) {
		// TODO Auto-generated method stub
		switch(view.getId()){
		case R.id.btLogin:
			user.userId=etUserId.getText().toString();
			user.role = ActivityUtil.getRole(spRole);
			paramsList.clear();
			paramsList.put("param", gson.toJson(user));
			paramsList.put("password", getEditTextString(etPassword));
			addPostRequest("login", paramsList, 0);
			sendPostRequest();
			break;
		case R.id.btRegister:
			Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.btSureUrl:
			ShareUtil.BASE_URL="http://"+getEditTextString(etUrl)+":8080/pmh/";
			ToastUtil.show(this, ShareUtil.BASE_URL);
		}
	}

	@Override
	public void afterPost(String result, int requestCode,Map<String, String> request) {
		// TODO Auto-generated method stub
		gsonBean = gson.fromJson(result, GsonBean.class);
		if(gsonBean.state==FinalValue.SUCCESS){
			HttpUtil.userString = gson.toJson(user);
			Intent intent = null;
			switch(user.role){
			case FinalValue.STUDENT:
				intent = new Intent(MainActivity.this,WritePaperActivity.class);
				break;
			case FinalValue.WORKER:
				intent = new Intent(MainActivity.this,WorkerHomeActivity.class);
				break;
			case FinalValue.MANAGER:
				intent = new Intent(MainActivity.this,ManagerWorkActivity.class);
				break;
			}
			
			startActivity(intent);
		}else{
			ToastUtil.show(this, "账号或密码错误");
		}
	}
	

}
